//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package events_subscribe

import (
	"fmt"

	"atomgit.com/openlinksaas/proto-gen-go.git/events/events_harbor"
	"atomgit.com/openlinksaas/proto-gen-go.git/events_api"
)

func processHarborEvent(event *events_api.Event, cfgItemList []*CfgItem) (bool, error) {
	var err error
	var msg string

	{
		pushArtifactEvent := &events_harbor.PushArtifactEvent{}
		if event.EventData.MessageIs(pushArtifactEvent) {
			err = event.EventData.UnmarshalTo(pushArtifactEvent)
			if err != nil {
				return false, err
			}

			msg = fmt.Sprintf("%s 在项目 %s 推送工件 %s。", event.UserDisplayName, event.ProjectName,
				pushArtifactEvent.EventData.Repository.RepoFullName)
			for _, cfgItem := range cfgItemList {
				if cfgItem.eventCfg.HarborEvCfg.PushArtifact {
					sendChatMsg(msg, cfgItem.subItem)
				}
			}
			return true, nil
		}
	}

	{
		deleteArtifactEvent := &events_harbor.DeleteArtifactEvent{}
		if event.EventData.MessageIs(deleteArtifactEvent) {
			err = event.EventData.UnmarshalTo(deleteArtifactEvent)
			if err != nil {
				return false, err
			}

			msg = fmt.Sprintf("%s 在项目 %s 删除工件 %s。", event.UserDisplayName, event.ProjectName,
				deleteArtifactEvent.EventData.Repository.RepoFullName)
			for _, cfgItem := range cfgItemList {
				if cfgItem.eventCfg.HarborEvCfg.DeleteArtifact {
					sendChatMsg(msg, cfgItem.subItem)
				}
			}
			return true, nil
		}
	}

	{
		uploadChartEvent := &events_harbor.UploadChartEvent{}
		if event.EventData.MessageIs(uploadChartEvent) {
			err = event.EventData.UnmarshalTo(uploadChartEvent)
			if err != nil {
				return false, err
			}

			msg = fmt.Sprintf("%s 在项目 %s 上传chart %s。", event.UserDisplayName, event.ProjectName,
				uploadChartEvent.EventData.Repository.RepoFullName)
			for _, cfgItem := range cfgItemList {
				if cfgItem.eventCfg.HarborEvCfg.UploadChart {
					sendChatMsg(msg, cfgItem.subItem)
				}
			}
			return true, nil
		}
	}

	{
		deleteChartEvent := &events_harbor.DeleteChartEvent{}
		if event.EventData.MessageIs(deleteChartEvent) {
			err = event.EventData.UnmarshalTo(deleteChartEvent)
			if err != nil {
				return false, err
			}

			msg = fmt.Sprintf("%s 在项目 %s 删除chart %s。", event.UserDisplayName, event.ProjectName,
				deleteChartEvent.EventData.Repository.RepoFullName)
			for _, cfgItem := range cfgItemList {
				if cfgItem.eventCfg.HarborEvCfg.DeleteChart {
					sendChatMsg(msg, cfgItem.subItem)
				}
			}
			return true, nil
		}
	}

	return false, nil
}
